<?php
namespace app\index\controller\wanlshop;


use app\common\controller\Wanlshop;
use fast\Http;

/**
 * 身份证管理
 *
 * @icon fa fa-circle-o
 */
class Idcard extends Wanlshop
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];
    
    /**
     * Idcard模型对象
     * @var \app\common\model\user\Idcard
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\user\Idcard;

    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname','avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    //下载
    public function download($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //正面
        $image_front = $row['image_front'];
        $image_front = ROOT_PATH.'public'.$image_front;
        $image_front_end = strrpos($image_front,'.');
        $image_front_start = strrpos($image_front,'/');
        $new_front_file = str_replace(substr($image_front,$image_front_start ,$image_front_end - $image_front_start),'/'.$row['name'].'_'.$row['number'].'_正面',$image_front);
        copy($image_front, $new_front_file);
        //反面
        $image_back = $row['image_back'];
        $image_back = ROOT_PATH.'public'.$image_back;
        $image_back_end = strrpos($image_back,'.');
        $image_back_start = strrpos($image_back,'/');
        $new_back_file = str_replace(substr($image_back,$image_back_start ,$image_back_end - $image_back_start),'/'.$row['name'].'_'.$row['number'].'_反面',$image_back);
        copy($image_back, $new_back_file);


        $tmpDir = ROOT_PATH.'public/uploads/zip/';

        if (!file_exists($tmpDir)) {
            //创建文件夹
            mkdir($tmpDir, 0777, true);
        }
        $zipName = $row['name'].'_'.$row['number'] . '.zip'; // 压缩包文件名
        $zipNameUrl = $tmpDir . $zipName; // 文件路径
        $zip = new \ZipArchive();

        if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
            //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
            if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                return  '下载失败，文件夹不存在';
            }
        }
        //抓取图片内容
        $frontFileContent = file_get_contents($new_front_file);
        //添加图片
        $zip->addFromString(basename($new_front_file), $frontFileContent);
        //抓取图片内容
        $backFileContent = file_get_contents($new_back_file);
        //添加图片
        $zip->addFromString(basename($new_back_file), $backFileContent);
        // 关闭
        $zip->close();

        //没有文件
        if (!file_exists($zipNameUrl)) {
            return '下载失败，图片不存在或无法下载';
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . $zipName); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器，文件大小

        // 下面2步必须要
        ob_clean();
        flush();

        @readfile($zipNameUrl);
        unlink($zipNameUrl); // 删除文件
        exit;
    }

    //批量下载
    public function downloads(){
        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->select();
            $tmpDir = ROOT_PATH.'public/uploads/zip/';

            if (!file_exists($tmpDir)) {
                //创建文件夹
                mkdir($tmpDir, 0777, true);
            }
            $zipName = date('His') . mt_rand(1000, 9999) . '.zip'; // 压缩包文件名
            $zipNameUrl = $tmpDir . $zipName; // 文件路径
            $zip = new \ZipArchive();

            if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
                //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
                if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                    // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                    return  '下载失败，文件夹不存在';
                }
            }
            foreach ($list as $row) {
                //正面
                $image_front = $row['image_front'];
                $image_front = ROOT_PATH.'public'.$image_front;
                $image_front_end = strrpos($image_front,'.');
                $image_front_start = strrpos($image_front,'/');
                $new_front_file = str_replace(substr($image_front,$image_front_start ,$image_front_end - $image_front_start),'/'.$row['name'].'_'.$row['number'].'_正面',$image_front);
                copy($image_front, $new_front_file);
                //反面
                $image_back = $row['image_back'];
                $image_back = ROOT_PATH.'public'.$image_back;
                $image_back_end = strrpos($image_back,'.');
                $image_back_start = strrpos($image_back,'/');
                $new_back_file = str_replace(substr($image_back,$image_back_start ,$image_back_end - $image_back_start),'/'.$row['name'].'_'.$row['number'].'_反面',$image_back);
                copy($image_back, $new_back_file);
                //抓取图片内容
                $frontFileContent = file_get_contents($new_front_file);
                //添加图片
                $zip->addFromString(basename($new_front_file), $frontFileContent);
                //抓取图片内容
                $backFileContent = file_get_contents($new_back_file);
                //添加图片
                $zip->addFromString(basename($new_back_file), $backFileContent);

            }
            // 关闭
            $zip->close();

            //没有文件
            if (!file_exists($zipNameUrl)) {
                return '下载失败，图片不存在或无法下载';
            }

            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header('Content-disposition: attachment; filename=' . $zipName); //文件名
            header("Content-Type: application/zip"); //zip格式的
            header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
            header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器，文件大小

            // 下面2步必须要
            ob_clean();
            flush();

            @readfile($zipNameUrl);
            unlink($zipNameUrl); // 删除文件
            exit;
        }
    }

}
